'use strict'

import { getMessageTrayIcon, getNoMessageTrayIcon } from './logo'
import logo from './logo'
import { app, protocol, BrowserWindow, ipcMain, Tray, Menu, Notification, shell } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let win = null
let child = null
let tray = null
let notify = null
let badgeNum = 0
let _flickerTimer = null
let messageTrayIcon = getMessageTrayIcon()
let noMessageTrayIcon = getNoMessageTrayIcon()

async function createWindow() {
  win = new BrowserWindow({
    width: 1200,//960
    height: 780,//720
    minWidth: 800,
    minHeight: 600,
    useContentSize: true,
    center: true,
    frame: false,
    resizable: true,
    show: false,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })


  win.once('ready-to-show', () => {
    win.show()
  })
  // win.on('hide', () => {
  //   win.webContents.send('winEvent','hide');
  // })
  // win.on('show', () => {
  //   win.webContents.send('winEvent','show');
  // })
  // win.on('minimize', () => {
  //   win.webContents.send('winEvent','minimize');
  // })
  // win.on('restore', () => {
  //   win.webContents.send('winEvent','restore');
  // })
  win.on('blur', () => {
    win.webContents.send('winEvent','blur');//失去焦点
  })
  win.on('focus', () => {
    win.webContents.send('winEvent','focus');//获得焦点
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }



}



ipcMain.on('MAINWIN:window-close', () => win.hide())
ipcMain.on('MAINWIN:window-max', () => win.maximize())
ipcMain.on('MAINWIN:window-unmax', () => win.unmaximize())
ipcMain.on('MAINWIN:window-min', () => win.minimize())
ipcMain.on('LOGINWIN:window-close', () => app.quit())
ipcMain.on('MAINWIN:badge', (e, count) => {
  badgeNum = count
  app.setBadgeCount(count)
  flicker(count)
  //macos弹跳
  // if (app.dock && count>0) {
  //   app.dock.show()
  //   app.dock.bounce('critical')
  // }
})
ipcMain.on('MAINWIN:openWin', (e, _obj) => {
  var obj = JSON.parse(_obj);
  shell.openExternal(obj.url);
})
ipcMain.on('MAINWIN:notify', (e, _msg) => {
  var msg = JSON.parse(_msg);
  var content = transferContent(msg.content);
  notify = new Notification({
    title: msg.username,
    body: content,
    timeoutType: 'never',
    icon: logo
  })
  notify.show()
  notify.on('click', ()=>{
    win.show();win.focus();
    win.webContents.send('winEvent','notifyClick');
  })
})
app.whenReady().then(()=>{
  tray = new Tray(noMessageTrayIcon)
  tray.setToolTip('东翔OA')
  tray.on('click', () => {
    win.show();win.focus();
    if(badgeNum>0){
      win.webContents.send('winEvent','notifyClick');
    }
  })
  // tray.on('double-click', () => {
  //   win.show();win.focus();
  // })
  const menu = [
    {
      label: '显示窗口',
      click: () => {win.show();win.focus();}
    },
    {
      label: '退出',
      click: () => app.quit()
    }
  ]

  // 绑定菜单
  tray.setContextMenu(Menu.buildFromTemplate(menu))



})


function flicker(is) {
  if (is) {
    let icon = getMessageTrayIcon()
    if (_flickerTimer !== null) return
    _flickerTimer = setInterval(() => {
      tray.setImage(icon)
      icon = icon === messageTrayIcon ? noMessageTrayIcon : messageTrayIcon
    }, 500)
  } else {
    clearInterval(_flickerTimer)
    _flickerTimer = null
    tray.setImage(noMessageTrayIcon)
  }
}

var faces = function() {
  var alt = ["[微笑]", "[嘻嘻]", "[可爱]", "[坏笑]", "[偷笑]", "[害羞]", "[哈哈]", "[失望]", "[悲伤]", "[撇嘴]", "[委屈]", "[汗]", "[晕]",
      "[鄙视]", "[大哭]", "[抓狂]", "[吃惊]", "[疑问]", "[闭嘴]", "[嘘]", "[哈欠]", "[鼓掌]", "[吐舌]", "[馋嘴]", "[奋斗]", "[拜拜]", "[拥抱]",
      "[怒]", "[抱拳]", "[ok]", "[耶]", "[good]", "[NO]", "[握手]", "[来]", "[花]"
    ],
    arr = {};
  alt.forEach(function(index, item) {
    // #ifdef MP-WEIXIN
    arr[index] = 'http://file.fanyuinc.com/face/' + item + '.gif';
    // #endif
    // #ifdef APP-PLUS || H5
    arr[index] = 'http://file.fanyuinc.com/face/' + item + '.gif';
    // #endif
  });
  return arr;
}()

function transferContent(content) {
  content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
    .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@
    // .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
    //   var alt = face.replace(/^face/g, '');
    //   return '<img style="vertical-align:middle;width:15px;" src="' + faces[alt] + '"/>';
    // })
    .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
      return "[图片]";
    })
    .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
      var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
      var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
      if (!href) return str;
      return "[文件] " + text;
    })
    .replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
      return "[语音]";
    })
    .replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
      return "[视频]";
    })
    .replace(/json\[.*\]/g, function(json) { //转义json
      var str = json.replace(/(^json\[)|(\]$)/g, '');
      str = str.replace(/&amp;/g, '&');
      str = str.replace(/&lt;/g, '<');
      str = str.replace(/&gt;/g, '>');
      str = str.replace(/&quot;/g, '"');
      str = str.replace(/&#039;/g, "'");
      str = str.replace(/&#39;/g, "'");
      var obj = JSON.parse(str);
      return obj.title;
    });
  return content;
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
